<template>
  <a-modal
    v-model:open="visible"
    :title="modalTitle"
    width="800px"
    @cancel="handleCancel"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      layout="vertical"
    >
      <!-- 基本信息 -->
      <div class="form-section">
        <h3 class="section-title">基本信息</h3>
        <div class="form-row">
          <div class="form-column">
            <a-form-item label="组合名称" name="name" required>
              <a-input
                v-model:value="formData.name"
                placeholder="请输入组合名称"
                size="large"
              />
            </a-form-item>
          </div>
          <div class="form-column">
            <a-form-item label="规格" name="specification">
              <a-input
                v-model:value="formData.specification"
                placeholder="请输入规格"
                size="large"
              />
            </a-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="form-column">
            <a-form-item label="单位" name="unit">
              <a-input
                v-model:value="formData.unit"
                placeholder="请输入单位"
                size="large"
              />
            </a-form-item>
          </div>
          <div class="form-column">
            <a-form-item label="描述" name="description">
              <a-textarea
                v-model:value="formData.description"
                placeholder="请输入组合描述"
                :rows="3"
              />
            </a-form-item>
          </div>
        </div>
      </div>

      <!-- 组合项目 -->
      <div class="form-section">
        <div class="section-header">
          <h3 class="section-title">组合项目</h3>
          <a-button type="primary" @click="showAddItemModal">
            <template #icon><Plus /></template>
            添加项目
          </a-button>
        </div>

        <div class="items-table">
          <a-table
            :columns="itemColumns"
            :data-source="formData.items"
            :pagination="false"
            size="small"
          >
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.key === 'quantity'">
                <a-input-number
                  v-model:value="record.quantity"
                  :min="1"
                  :precision="0"
                  size="small"
                  style="width: 80px"
                />
              </template>
              <template v-else-if="column.key === 'action'">
                <a-button
                  type="link"
                  size="small"
                  danger
                  @click="removeItem(index)"
                >
                  <template #icon><Trash2 /></template>
                  删除
                </a-button>
              </template>
            </template>
          </a-table>
        </div>
      </div>
    </a-form>

    <template #footer>
      <a-space>
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" :loading="saving" @click="handleSave">
          保存
        </a-button>
      </a-space>
    </template>

    <!-- 添加项目模态框 -->
    <a-modal
      v-model:open="addItemModalVisible"
      title="添加项目"
      width="600px"
      @cancel="handleAddItemCancel"
    >
      <div class="add-item-content">
        <a-form layout="vertical">
          <a-form-item label="选择商品">
            <a-select
              v-model:value="selectedProductId"
              placeholder="请选择商品"
              style="width: 100%"
              show-search
              :filter-option="filterOption"
            >
              <a-select-option
                v-for="product in availableProducts"
                :key="product.id"
                :value="product.id"
              >
                {{ product.name }} - {{ product.specification }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="数量">
            <a-input-number
              v-model:value="selectedQuantity"
              :min="1"
              :precision="0"
              style="width: 100%"
            />
          </a-form-item>
        </a-form>
      </div>

      <template #footer>
        <a-space>
          <a-button @click="handleAddItemCancel">取消</a-button>
          <a-button type="primary" @click="handleAddItem"> 添加 </a-button>
        </a-space>
      </template>
    </a-modal>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue';
import { message } from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue';
import { Plus, Trash2 } from '@vben/icons';

// 定义props
interface Props {
  visible: boolean;
  scenario: string;
  combination?: any;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  scenario: 'prescription',
  combination: null,
});

// 定义emits
const emit = defineEmits<{
  'update:visible': [value: boolean];
  save: [combination: any]
}>();

// 响应式数据
const formRef = ref<FormInstance>();
const saving = ref(false);
const addItemModalVisible = ref(false);
const selectedProductId = ref('');
const selectedQuantity = ref(1);

// 表单数据
const formData = reactive({
  name: '',
  specification: '',
  unit: '',
  description: '',
  items: [] as any[],
});

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入组合名称',trigger: 'blur' }],
};

// 表格列定义
const itemColumns = [
  {
    title: '商品名称',
    dataIndex: 'name',
    key: 'name',
    width: 200,
  },
  {
    title: '规格',
    dataIndex: 'specification',
    key: 'specification',
    width: 150,
  },
  {
    title: '单位',
    dataIndex: 'unit',
    key: 'unit',
    width: 80,
  },
  {
    title: '数量',
    key: 'quantity',
    width: 100,
  },
  {
    title: '操作',
    key: 'action',
    width: 80,
  },
];

// 模拟可用商品数据
const availableProducts = ref([
  {
    id: '1',
    name: '阿莫西林',
    specification: '0.25g*24粒',
    unit: '盒',
  },
  {
    id: '2',
    name: '维生素C',
    specification: '100mg*100片',
    unit: '瓶',
  },
  {
    id: '3',
    name: '头孢克肟',
    specification: '0.1g*12粒',
    unit: '盒',
  },
  {
    id: '4',
    name: '布洛芬',
    specification: '0.2g*20片',
    unit: '盒',
  },
]);

// 计算属性
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value),
});

const modalTitle = computed(() => {
  return props.combination ? `编辑组合(${props.combination.name})` : '添加组合';
});

// 方法
const filterOption = (input: string, option: any) => {
  return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

const showAddItemModal = () => {
  addItemModalVisible.value = true;
  selectedProductId.value = '';
  selectedQuantity.value = 1;
};

const handleAddItem = () => {
  if (!selectedProductId.value) {
    message.warning('请选择商品');
    return;
  }

  const product = availableProducts.value.find(
    (p) => p.id === selectedProductId.value,
  );
  if (!product) {
    message.error('商品不存在');
    return;
  }

  const newItem = {
    id: Date.now().toString(),
    productId: product.id,
    name: product.name,
    specification: product.specification,
    unit: product.unit,
    quantity: selectedQuantity.value,
  };

  formData.items.push(newItem);
  addItemModalVisible.value = false;
  message.success('添加成功');
};

const handleAddItemCancel = () => {
  addItemModalVisible.value = false;
};

const removeItem = (index: number) => {
  formData.items.splice(index, 1);
  message.success('删除成功');
};

const handleSave = async () => {
  try {
    await formRef.value?.validate();
    saving.value = true;

    // 模拟保存请求
    await new Promise((resolve) => setTimeout(resolve, 1000));

    const combinationData = {
      ...formData,
      id: props.combination?.id,
      scenario: props.scenario,
    };

    emit('save', combinationData);
    message.success('保存成功');
    visible.value = false;
  } catch (error) {
    console.error('表单验证失败:', error);
  } finally {
    saving.value = false;
  }
};

const handleCancel = () => {
  visible.value = false;
  resetForm();
};

const resetForm = () => {
  formData.name = '';
  formData.specification = '';
  formData.unit = '';
  formData.description = '';
  formData.items = [];
  formRef.value?.resetFields();
};

// 监听props变化，初始化表单数据
watch(
  () => props.visible,
  (newVisible) => {
    if (newVisible) {
      if (props.combination) {
        // 编辑模式，填充现有数据
        Object.assign(formData, {
          ...props.combination,
          items: [...props.combination.items],
        });
      } else {
        // 新增模式，重置表单
        resetForm();
      }
    }
  },
);
</script>

<style scoped>
.form-section {
  margin-bottom: 24px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e8e8e8;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.form-row {
  display: flex;
  gap: 24px;
}

.form-column {
  flex: 1;
  min-width: 0;
}

.items-table {
  border: 1px solid #e8e8e8;
  border-radius: 4px;
}

.add-item-content {
  padding: 16px 0;
}
</style>
